package com.lxz.jucdemo.pool;

import org.springframework.scheduling.concurrent.DefaultManagedAwareThreadFactory;

import java.util.concurrent.*;

/**
 * @Author: 刘新智
 * @Date: 2025/10/27 10:57
 * @Description: 线程池
 * @Version: v1.0
 */
public class PoolTest {
    public static void main(String[] args) {
        /**
           三大方法（不建议使用Executors创建线程池）
         **/
//        ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();// 单线程线程池
//        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);// 固定大小线程池
//        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();// 缓存线程池
//        try {
//            for (int i = 1; i <=100 ; i++) {
//                cachedThreadPool.execute(()->{
//                    System.out.println(Thread.currentThread().getName()+"正在执行");
//                });
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        } finally {
//            cachedThreadPool.shutdown();
//        }

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,// 核心线程数
                5,// 最大线程数
                1L,// 线程空闲时间
                TimeUnit.SECONDS,// 时间单位
                new LinkedBlockingDeque<>(5),// 阻塞队列
                new DefaultManagedAwareThreadFactory(),// 线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy()// 拒绝策略
        );
        try {
            for (int i = 1; i <=1000 ; i++) {
                threadPoolExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"正在执行");
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPoolExecutor.shutdown();
        }
    }
}
